<template>
  <!-- 用户管理 -->
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :span="6" :xs="24">
        <div class="mainbox-left">

          <div class="box-card">
            <!-- 搜索栏 -->
            <el-input
              v-model.trim="filterText"
              prefix-icon="el-icon-search"
              placeholder="输入搜索组织名称"
              maxlength="30"
              style="margin: 20px 0;"
            />
            <el-tree
              ref="tree"
              :empty-text="$store.getters.dataText"
              :style="{'--lightOpacity':lightTheme}"
              class="left-tree"
              :data="tree"
              :load="load"
              lazy
              :props="defaultProps"
              :default-expand-all="false"
              :expand-on-click-node="false"
              :highlight-current="true"
              :current-node-key="currentKey"
              :filter-node-method="filterNode"
              node-key="id"
              @node-click="handleNodeClick"
            >
              <span slot-scope="{ node}">
                <el-tooltip class="item" effect="dark" :content="node.label" placement="bottom-start">
                  <span class="tree-name">{{ node.label }}</span>
                </el-tooltip>
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <!-- 主内容 -->
      <el-col :span="18" :xs="24" style="padding-left: 0px">
        <div class="none2-border3 userlist mainbox">
          <!-- 顶部操作 -->
          <div class="filter-container">
            <el-form ref="filterFormRef" :inline="true" :model="filterForm">
              <el-form-item label="账号:" prop="account">
                <el-input
                  v-model.trim="filterForm.account"
                  placeholder="请输入内容"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  @keyup.enter.native="handleFilter"
                />
              </el-form-item>
              <el-form-item label="姓名:" prop="realName">
                <el-input
                  v-model.trim="filterForm.realName"
                  placeholder="请输入内容"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  @keyup.enter.native="handleFilter"
                />
              </el-form-item>
            </el-form>
            <div class="flex-1" />
            <el-button type="primary" @click="handleFilter">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
          <!-- 表格 -->
          <div class="table-container table-fullscreen">
            <div class="table-opt-container">
              <el-button v-permission="['ORG_USER_ADD_BUTTON']" class="filter-item" icon="el-icon-plus" type="primary" @click="createUserInfo()">
                新增
              </el-button>
              <el-dropdown style="margin-left: 10px">
                <el-button
                  v-permission="['ORG_USER_EXPORT_BUTTON']"
                  :disabled="list.length<=0"
                  size="medium"
                >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    @click.native="handleDownload('all')"
                  >导出所有</el-dropdown-item>
                  <el-dropdown-item
                    @click.native="handleDownload()"
                  >导出选中</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div class="flex-1" />
              <dt-dialog-column :columns="columns" @queryTable="getList" />
            </div>
            <el-table
              ref="table"
              v-loading="listLoading"
              :data="list"
              border
              highlight-current-row
              :row-key="getRowKey"
              style="width: 100%;text-align:center"
              :header-cell-style="headerCellStyle"
              @sort-change="sortChange"
              @selection-change="handleSelectionChange"
            >
              <template slot="empty">
                <p>{{ $store.getters.dataText }}</p>
              </template>
              <el-table-column
                type="selection"
                width="55"
                :reserve-selection="true"
              />
              <el-table-column
                fixed="left"
                type="index"
                label="序号"
                width="70"
                :index="table_index"
              />
              <el-table-column
                v-if="columns[0].show"
                key="account"
                prop="account"
                label="账号"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="columns[1].show"
                key="realName"
                prop="realName"
                label="姓名"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="columns[2].show"
                key="positionName"
                prop="positionName"
                label="职位"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="columns[3].show"
                key="phone"
                prop="phone"
                label="手机"
              />
              <el-table-column
                v-if="columns[4].show"
                key="statusFlag"
                prop="statusFlag"
                class-name="status-col"
                label="启用状态"
              >
                <template slot-scope="{ row, $index }">
                  <el-switch
                    :disabled="disabled(row) || !hasAuth"
                    :value="row.statusFlag"
                    :active-value="1"
                    :inactive-value="2"
                    @change="statusChange(row.statusFlag, row, $index)"
                  />
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" label="操作" :fixed="$store.getters.device == 'mobile'? null :'right' " class-name="small-padding fixed-width" width="312">
                <template slot-scope="{ row }">
                  <el-button v-permission="['ORG_USER_UPDATE_BUTTON']" :disabled="disabled(row)" size="mini" @click="editUserInfo(row)">
                    修改
                  </el-button>
                  <el-button v-permission="['ORG_USER_ASSIGN_ROLE']" style="padding: 7px" :disabled="disabled(row)" size="mini" @click="setRole(row)">
                    分配角色
                  </el-button>
                  <el-button v-permission="['ORG_USER_RESET_PASSWORD']" style="padding: 7px" size="mini" @click="resetPassWord(row)">
                    重置密码
                  </el-button>
                  <el-button v-permission="['ORG_USER_DEL_BUTTON']" size="mini" :disabled="disabled(row)" type="danger" @click="removeUser(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <dt-pagination
              v-show="total > 0"
              :total="total"
              :page.sync="filterForm.pageNo"
              :limit.sync="filterForm.pageSize"
              @pagination="getList"
            />
          </div>
          <!-- 新增修改 -->
          <dtDialog
            :title="textMap[dialogStatus]"
            :visible.sync="dialogFormVisible"
            :is-loading="loading"
            @closeDialog="resetTemp"
            @comfirmBtn="dialogStatus === 'create' ? createData() : updateData()"
          >
            <el-form
              ref="dataForm"
              slot="content"
              :rules="rules"
              :model="temp"
              label-position="right"
              :label-width="dialogStatus === 'create'? '82px':'54px'"
            >
              <!-- 基本信息 -->
              <!-- <el-card class="box-card"> -->
              <div class="title">基本信息</div>
              <el-form-item v-if="dialogStatus === 'create'" label="账号" prop="account">
                <el-input v-model.trim="temp.account" maxlength="20" show-word-limit class="limit" />
              </el-form-item>
              <el-form-item v-if="dialogStatus === 'create'" label="密码" type="password" prop="password">
                <el-input v-model.trim="temp.password" type="password" maxlength="20" class="limit" autocomplete="new-password" />
              </el-form-item>
              <el-form-item v-if="dialogStatus === 'create'" label="重复密码" type="password" prop="password2">
                <el-input v-model.trim="temp.password2" type="password" maxlength="20" class="limit" autocomplete="new-password" />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio v-model="temp.sex" label="M">男</el-radio>
                <el-radio v-model="temp.sex" label="F">女</el-radio>
              </el-form-item>
              <el-form-item label="姓名" prop="realName">
                <el-input v-model.trim="temp.realName" maxlength="20" show-word-limit class="limit" />
              </el-form-item>
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model.trim="temp.nickName" maxlength="20" show-word-limit class="limit" />
              </el-form-item>
              <el-form-item label="生日" prop="birthday">
                <el-date-picker v-model="temp.birthday" value-format="yyyy-MM-dd" style="width: 100%" type="date" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model.trim="temp.email" maxlength="50" show-word-limit class="limit" />
              </el-form-item>
              <el-form-item label="手机" prop="phone">
                <el-input v-model.trim="temp.phone" maxlength="11" show-word-limit class="limit" />
              </el-form-item>
              <el-form-item label="电话" prop="tel">
                <el-input v-model.trim="temp.tel" />
              </el-form-item>
              <!-- </el-card> -->
              <!-- 职务信息 -->
              <!-- <el-card class="box-card" style="margin-top: 10px"> -->
              <div class="title">职务信息</div>
              <el-form-item label="机构" prop="orgId">
                <el-popover v-model="editUservisible" placement="top-start" trigger="click">
                  <el-tree
                    class="tree"
                    width="100%"
                    :data="treePopover"
                    :load="loadPopover"
                    lazy
                    :props="defaultProps"
                    :default-expand-all="false"
                    :expand-on-click-node="false"
                    @node-click="selectOrg"
                  />
                  <el-input slot="reference" v-model="orgName" :readonly="false" @focus="orgFocus" @input="orgInputchange" />
                </el-popover>
              </el-form-item>
              <el-form-item label="职位" prop="positionId">
                <el-select v-model="temp.positionId" style="width: 100%" class="filter-item">
                  <el-option
                    v-for="item in positionList"
                    :key="item.positionId"
                    :label="item.name"
                    :value="item.positionId"
                  />
                </el-select>
              </el-form-item>
              <!-- </el-card> -->
            </el-form>
          </dtDialog>
          <!-- 角色 -->
          <dtDialog
            title="授权角色"
            :visible.sync="roleDialogFormVisible"
            :is-loading="loading"
            @closeDialog="closeRoleDialog()"
            @comfirmBtn="submitRole()"
          >
            <el-form
              ref="roleDataForm"
              slot="content"
              :rules="roleRules"
              :model="roleTemp"
              label-position="right"
              label-width="82px"
              style="width: 100%"
            >
              <el-form-item label="选择角色" prop="grantRoleIdList">
                <el-select v-model="roleTemp.grantRoleIdList" clearable multiple placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-form>
          </dtDialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { hasAuth } from '@/framework/utils/hasAuth'
import hrOrganizationApi from '@/framework/api/hrOrganization'
import hrPositionApi from '@/framework/api/hrPosition'
import sysUserApi from '@/framework/api/sysUser'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
import roleApi from '@/framework/api/role'
import { getPwdRole } from '@/framework/api/sysUser'
import {
  checkEmail,
  checkUserName,
  checkAccountName
  // checkPhone
} from '@/framework/utils/validate'
export default {
  name: 'OrgUser',
  mixins: [dialogColumn],
  data() {
    // 对密码进行自定义验证
    const validateNewPwd = (rule, value, callback) => {
      if (!value) {
        callback('请输入密码')
      } else if (this.pwdreg.test(value) === false) {
        callback(this.pwdregcon)
      } else {
        callback()
      }
    }
    // 重复密码校验
    const validateConfirmPwd = (rule, value, callback) => {
      if (!value) {
        callback('请再次输入新密码')
      } else if (value !== this.temp.password) {
        callback('两次密码输入不一致')
      } else {
        callback()
      }
    }
    // 账号校验
    const validateUserName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入账号'))
      } else if (!checkUserName(value)) {
        callback(new Error('账号长度1-20字母、数字组成（不区分大小写）'))
      } else {
        callback()
      }
    }
    // 姓名校验
    const validateAccountName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入姓名'))
      } else if (!checkAccountName(value)) {
        callback(new Error('姓名只能输入汉字、字母、数字'))
      } else callback()
    }
    // 邮箱校验
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!checkEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else callback()
    }
    // 手机号校验
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!this.validate.checkPhone(value)) {
        callback(new Error('手机号格式错误'))
      } else callback()
    }
    return {
      loading: false,
      filterText: '',
      hasAuth: hasAuth('ORG_USER_CHANGE_STATUS'),
      tree: [],
      treePopover: [],
      currentKey: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      filterForm: {
        account: '',
        realName: '',
        orgId: '',
        pageNo: 1,
        pageSize: 10
      },
      listLoading: false,
      list: [],
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改用户',
        create: '新增用户'
      },
      temp: {
        account: '',
        password: '',
        password2: '',
        orgId: '',
        sex: 'M',
        email: '',
        phone: '',
        realName: ''
      },
      orgName: '',
      selectId: '',
      selectData: '',
      positionList: [],
      // 列信息
      columns: [
        { prop: 'account', label: `账号`, show: true },
        { prop: 'realName', label: `姓名`, show: true },
        { prop: 'positionName', label: `职位`, show: true },
        { prop: 'phone', label: `手机`, show: true },
        { prop: 'statusFlag', label: `状态`, show: true }
      ],
      rules: {
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        }],
        account: [{
          required: true,
          trigger: 'change',
          validator: validateUserName
        }],
        password: [{
          required: true,
          trigger: 'change',
          validator: validateNewPwd
        }],
        password2: [{
          required: true,
          trigger: 'change',
          validator: validateConfirmPwd
        }],
        email: [{
          required: true,
          trigger: 'change',
          validator: validateEmail
        }],
        phone: [{
          required: true,
          trigger: 'change',
          validator: validatePhone
        }],
        // birthday: [{
        //   required: true,
        //   message: '请选择生日',
        //   trigger: 'change'
        // }],
        realName: [{
          required: true,
          trigger: 'blur',
          validator: validateAccountName
        }],
        orgId: [{
          required: true,
          message: '请选择机构',
          trigger: 'change'
        }]
      },
      roleDialogFormVisible: false,
      roleTemp: {
        grantRoleIdList: []
      },
      selectedOrg: {},
      roleRules: {
        grantRoleIdList: [{
          required: true,
          message: '请选择角色',
          trigger: 'change'
        }]
      },
      roleList: [],
      downloadLoading: false,
      multipleSelection: [],
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      orgTextMap: {
        update: '修改机构',
        create: '新增机构'
      },
      orgSubmitLoading: false,
      editUservisible: false,
      sysUserListLength: 0,
      cacheData: {},
      currentOrg: {}
    }
  },
  computed: {
    lightTheme() {
      return this.$store.state.settings.theme + '19'
    }
  },
  watch: {
    filterText(val) {
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: val }).then((res) => {
        const data = res.data.map((item, index) => {
          item.orgId = item.id
          item.orgName = item.name
          return item
        })
        this.tree = data
      })
    }
    // orgName(val) {
    //   setTimeout(() => {
    //     hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: val }).then((res) => {
    //       const data = res.data.map((item, index) => {
    //         item.orgId = item.id
    //         item.orgName = item.name
    //         return item
    //       })
    //       this.treePopover = data
    //     })
    //   }, 200)
    // }
  },
  created() {
    this.initTree()
  },
  methods: {
    disabled(row) {
      if (row.superAdminFlag == 'Y' || row.tenantAdminFlag == 'Y') {
        return true
      } else {
        return false
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 左侧树结构
    handleNodeClick(data) {
      this.filterForm.orgId = data.id
      this.selectedOrg = data
      this.currentKey = this.selectedOrg.id
      this.handleFilter()
    },
    orgBlur() {
      if (this.orgName == '') {
        // this.orgName = this.selectedOrg.name
        // this.temp.orgId = this.currentKey
        this.orgName = ''
        this.temp.orgId = ''
      }
    },
    orgInputchange() {
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: this.orgName }).then((res) => {
        const data = res.data.map((item, index) => {
          item.orgId = item.id
          item.orgName = item.name
          return item
        })
        this.treePopover = data
      })
      if (this.orgName == '') {
        // this.orgName = this.selectedOrg.name
        // this.temp.orgId = this.currentKey
        this.orgName = ''
        this.temp.orgId = ''
      }
    },
    orgFocus() {
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: this.orgName }).then((res) => {
        const data = res.data.map((item, index) => {
          item.orgId = item.id
          item.orgName = item.name
          return item
        })
        this.treePopover = data
      })
    },
    // 选择机构
    selectOrg(data) {
      this.editUservisible = false
      this.temp.orgId = data.id
      this.orgName = data.name
      this.currentOrg = data
    },
    // 获取左侧组织树
    initTree() {
      const that = this
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0 }).then((res) => {
        that.tree = res.data
        this.selectedOrg = res.data[0]
        this.currentKey = res.data[0].id
        this.getList()
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(res.data[0].id)
        })
      })
    },
    // 列表序号
    table_index(index) {
      return (this.filterForm.pageNo - 1) * this.filterForm.pageSize + index + 1
    },
    // 获取页面列表
    getList() {
      this.listLoading = true
      this.filterForm.orgId = this.selectedOrg.id
      sysUserApi.fetchPage(this.filterForm).then((res) => {
        this.list = res.data.rows
        this.total = res.data.totalRows
        this.sysUserListLength = res.data.rows.length
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 搜索
    handleFilter() {
      this.$refs.table.clearSelection()
      this.filterForm.pageNo = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.handleFilter()
    },
    // 获取职位列表
    getPositionList() {
      hrPositionApi.fetchList().then((res) => {
        /* this.positionList = res.data.filter((item, index, arr) => {
            return item.statusFlag === 1
          }) */
        this.positionList = res.data
      })
    },
    sortChange(data) {
      this.filterForm.sort = data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      if (data.order.startsWith('asc')) {
        this.filterForm.order = 'asc'
      } else {
        this.filterForm.order = 'desc'
      }
      this.getList()
      /* const {
          prop,
          order
        } = data
      /* if (prop === 'id') {
          this.sortByID(order)
        } */
    },
    statusChange(v, row, index) {
      const flag = (v === 1 ? 2 : 1)
      sysUserApi.changeStatus({
        statusFlag: flag,
        userId: row.userId
      }).then((res) => {
        this.$dtMessage({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        // this.list[index].statusFlag = flag
        this.getList()
      })
    },
    resetTemp() {
      this.temp = {
        account: '',
        password: '',
        orgId: '',
        sex: 'M'
      }
      this.orgName = ''
    },
    // 获取密码策略
    getPwdRole() {
      getPwdRole().then(res => {
        this.pwdrole = res.data
        this.pwdreg = new RegExp(this.pwdrole.pwdRegularExpression)
        this.pwdregcon = this.pwdrole.pwdRgDescribe
      })
    },
    createUserInfo(orgId, orgName) {
      this.getPositionList()
      this.getPwdRole()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.orgId = this.selectedOrg.id
      this.temp.name = this.selectedOrg.name
      this.orgName = this.selectedOrg.name
      this.currentOrg = this.selectedOrg
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    editUserInfo(row) {
      this.getPositionList()
      this.getPwdRole()
      const that = this
      this.dialogStatus = 'update'
      sysUserApi.detail(row.userId).then((res) => {
        this.cacheData = JSON.stringify(res.data)
        that.temp = Object.assign({}, res.data)
        this.temp.orgId = that.temp.orgId
        this.orgName = that.temp.orgName
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    /**
       * 在多级对象数组中查找
       * arr 多级数组
       * col 在对象中要查询匹配的属性名
       * value 匹配的值
       */
    findInTree(arr, col, value) {
      let res = {
        success: false,
        data: {}
      }
      for (const data of arr) {
        if (data[col] === value) {
          res.success = true
          res.data = data
        } else if (data.children && data.children.length > 0) {
          res = this.findInTree(data.children, col, value)
        }
        if (res.success) {
          break
        }
      }
      return res
    },
    // 修改用户请求
    updateData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          this.loading = true
          const tempData = Object.assign({}, this.temp)
          if (this.cacheData === JSON.stringify(this.temp)) {
            this.dialogFormVisible = false
            this.loading = false
          } else {
            try {
              await sysUserApi.edit(tempData)
              this.getList()
              this.dialogFormVisible = false
              this.$dtMessage({
                message: '修改成功',
                type: 'success'
              })
              this.loading = false
            } catch (error) {
              this.loading = false
            }
          }
        }
        this.loading = false
      })
    },
    // 创建用户请求
    async createData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          this.loading = true
          const tempData = Object.assign({}, this.temp)
          try {
            await sysUserApi.add(tempData)
            this.getList()
            this.dialogFormVisible = false
            this.$dtMessage({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
        // this.loading = false
      })
    },
    removeUser(row) {
      this.$dtMessageBox({ title: '提示', message: '确定要删除“' + row.account + '”吗?', type: 'warning' }).then(() => {
        sysUserApi.delete(row).then(res => {
          this.getList()
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
          // 解决勾选了一个数据后，再删除该数据，然后再进行导出的时候导出不提示"至少勾选一条数据"，并且可以导出导出的表为空的bug
          this.multipleSelection.forEach((item, index, multipleSelection) => {
            if (item.id === row.id) {
              multipleSelection.splice(index, 1)
              return multipleSelection
            } else {
              return multipleSelection
            }
          })
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    initRoleList() {
      roleApi.dropDown().then(res => {
        this.roleList = res.data
      })
    },
    setRole(row) {
      this.initRoleList()
      sysUserApi.detail(row.userId).then((res) => {
        const arr = res.data.grantRoleInfosList.map(el => {
          return el.roleId
        })
        this.roleTemp.grantRoleIdList = arr
        this.roleTemp.userId = res.data.userId
        this.roleDialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['roleDataForm'].clearValidate()
        })
      })
    },
    submitRole() {
      this.$refs['roleDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.roleTemp.select = this.roleTemp.grantRoleIdList.toString()
          try {
            sysUserApi.grantRole(this.roleTemp).then(res => {
              this.getList()
              this.roleDialogFormVisible = false
              this.$dtMessage({
                message: '授权成功',
                type: 'success'
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    closeRoleDialog() {
      // this.roleDialogFormVisible = false
      this.roleTemp = {
        grantRoleIdList: []
      }
    },
    resetPassWord(row) {
      const that = this
      this.$confirm('是否确认重置为默认密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sysUserApi.resetPwd(row).then((res) => {
          that.getList()
          that.$dtMessage({
            message: '重置成功',
            type: 'success'
          })
        })
      })
    },
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        sysUserApi.exportAllUser().then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '用户信息' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.downloadLoading = false
        })
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map(res => {
          return res.userId
        }).join(',')
        con = {
          userIds: ids,
          account: this.filterForm.account,
          realName: this.filterForm.realName,
          orgId: this.currentKey
        }
        this.downloadLoading = true
        sysUserApi.exportUser(con).then(res => {
          if (this.list == null) {
            this.$dtMessage({
              title: '失败',
              message: res.message,
              type: 'error',
              duration: 2000
            })
            this.downloadLoading = false
          } else {
            const blob = new Blob([res.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const objectUrl = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = objectUrl // 指定下载链接
            a.download = '用户信息' // 指定下载文件名
            a.click()
            URL.revokeObjectURL(a.href) // 释放URL对象
            this.downloadLoading = false
          }
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getRowKey(row) {
      return row.userId
    },
    // // 懒加载
    load(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
        return
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const data = res.data.map((item, index) => {
          this.selectedOrg = res.data[0]
          this.currentKey = res.data[0].id

          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(res.data[0].id)
          })
          return item
        })
        resolve(data)
      })
    },
    loadPopover(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const data = res.data
        resolve(data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .clearfix {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;
  }

    .left-tree{
      height:calc(100% - 52px)
    }
    ::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
      background-color:var(--lightOpacity)
    }
    ::v-deep .el-tree-node__content:hover, .el-upload-list__item:hover{
      background-color:var(--lightOpacity)
    }
.title{
  font-size: 16px;
  font-family: HarmonyOS Sans SC-Medium, HarmonyOS Sans SC;
  font-weight: 500;
  color: #131314;
  line-height: 24px;
  padding-bottom: 8px;
  border-bottom: 1px solid #EBEEF5;
  margin-bottom: 24px;
}

</style>
